/**
 * Copyright (c) 2015 Messcat. All rights reserved.
 */
package cc.messcat.web.system;

import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.constant.CommonRedisConstant;
import cc.messcat.common.model.JDBCSettingBean;
import cc.messcat.common.model.ResponseBean;
import cc.messcat.common.util.ResponseHandler;
import cc.messcat.entity.system.McUser;
import cc.messcat.service.system.SystemService;
import cc.messcat.service.system.UserService;
import cc.messcat.util.LevelUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统功能处理
 *
 * @author Panda
 * @version 1.0
 */
@Controller
public class SystemController {

	@Autowired
	private SystemService systemService;
	
	@Autowired
	private UserService userService;
	
	private String historyFilename =  "backup.history";
	
	@Autowired
	private JDBCSettingBean jdbcSettingBean;

	@Autowired
	private AreaAspect areaAspcet;
	
	/**
	 * 年度数据备份
	 * @return
	 */
	@RequestMapping("/annualBackup")
	@ResponseBody
	public Object annualBackup(	
		@RequestParam(name="origin",required=false) Integer origin,
		@RequestParam(name="derivation",required=false) Integer derivation,
		HttpSession session,
		HttpServletRequest request) {
		
		//防止重复操作
		Object obj = session.getServletContext().getAttribute("backup");
		if(obj != null) {
			return new ResponseBean(CommonConstant.FAIL_CODE_400, "当前正在备份",null);
		}
		McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
		if(user.getUserLevel().getLevel()>LevelUtil.ALL) {
			return new ResponseBean(CommonConstant.FAIL_CODE_400, "权限不足",null);
		}
		
		origin = origin == null || origin == 0 ? Calendar.getInstance().get(Calendar.YEAR) : origin;
		derivation = derivation == null || derivation == 0 ? origin + 1 : derivation;
		
		Map flag = new HashMap<>(1);
		session.getServletContext().setAttribute("backup",flag);
		//备份进度
		session.setAttribute("backupProgress", new HashMap<>(2));
		session.getServletContext().setAttribute("backupProgress",session.getAttribute("backupProgress"));
		Map result;
		try {
			result = systemService.annualBackup(origin,derivation,session,request);
			session.getServletContext().removeAttribute("backup");
			session.getServletContext().removeAttribute("backupProgress");
			session.removeAttribute("backupProgress");

			session.setAttribute("businessAnnual", systemService.getBusinessAnnual());
			session.getServletContext().setAttribute("businessAnnual", systemService.getBusinessAnnual());

			return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_SUCCESS, result);
		} catch (Exception e) {
			e.printStackTrace();
			session.removeAttribute("backupProgress");
			session.getServletContext().removeAttribute("backupProgress");
			session.getServletContext().removeAttribute("backup");
			return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_FAIL,null);
		}
	}
	
	/**
	 * 数据恢复
	 */
	@RequestMapping("restore")
	@ResponseBody
	public Object restore(HttpSession session,
		@RequestParam(name="origin",required=false) Integer origin,
		@RequestParam(name="derivation",required=false) Integer derivation) {
		
		McUser user = userService.retrieveUserByUsername((String) session.getAttribute(CommonRedisConstant.REDIS_KEY_LOGIN_USER));
		if(user.getUserLevel().getLevel()>LevelUtil.ALL) {
			return new ResponseBean(CommonConstant.FAIL_CODE_400, "权限不足",null);
		}
		
		Map<String,String> result = systemService.restore(origin, derivation);

		session.setAttribute("businessAnnual", systemService.getBusinessAnnual());
		session.getServletContext().setAttribute("businessAnnual", systemService.getBusinessAnnual());

		return new ResponseBean(CommonConstant.SUCCESS_CODE_200,result.get("msg"),null);
	}
	
	/**
	 * 备份进度获取
	 * @param session
	 * @return
	 */
	@RequestMapping("getBackupProgress")
	@ResponseBody
	public Object getBackupProgress(HttpSession session) {
		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_SUCCESS,session.getServletContext().getAttribute("backupProgress"));
	}
	
	/**
	 * 历史记录文件获取
	 * @throws IOException
	 */
	@RequestMapping("/getHistory")
	public void getHistory(HttpServletResponse response) throws IOException {
		File backupFilePath = new File(jdbcSettingBean.getDataPath());
		File historyFile =  new File(backupFilePath+"/"+historyFilename);
		
		response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode("数据备份历史记录","UTF-8")+".txt");
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		
		FileUtils.copyFile(historyFile, response.getOutputStream());
	}
	

	@RequestMapping("/download")
	public ResponseEntity<byte[]> download() throws Exception {
		File file = systemService.backupData();
		return ResponseHandler.downloadFile(file);
	}


	/**
	 * 刷新系统
	 */
	@RequestMapping("/refresh")
	@ResponseBody
	public Object refresh(HttpSession session)  {
		//年度
		session.setAttribute("businessAnnual", systemService.getBusinessAnnual());
		session.getServletContext().setAttribute("businessAnnual", systemService.getBusinessAnnual());

		//区域缓存更新
		areaAspcet.updateAreaCacha();

		return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_SUCCESS,"OK");
	}
}